#!/bin/sh
#
### BEGIN INIT INFO
# Provides: xserver
# Required-Start: $local_fs $remote_fs dbus
# Required-Stop: $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

# Don't reboot when failed
stoponfail="1"
EXTRA_ENVS="LANG=$LANG "
EULA_DIR="@EULA_DIR@"
EXTRA_ENVS="$EXTRA_ENVS EULA_DIR=$EULA_DIR"

export PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin

[ -z "$CMDLINE" ] && read CMDLINE < /proc/cmdline
for x in $CMDLINE; do
        case $x in
        cmdline)
            cmdline=1
            ;;
        headless)
            headless=1
            ;;
        kbdtype=*)
            kbdtype="${x#kbdtype=}"
            ;;
        keymap=*)
            keymap="${x#keymap=}"
            ;;
        ks=*)
            ks="${x#ks=}"
            ;;
        lang=*)
            lang="${x#lang=}"
            ;;
        bootifonly=*)
            bootifonly="${x#bootifonly=}"
            ;;
        stoponfail=*)
            stoponfail="${x#stoponfail=}"
            ;;
        liveinst)
            liveinst=1
            ;;
        loglevel=*)
            loglevel="${x#loglevel=}"
            ;;
        mpath)
            mpath=1
            ;;
        noinstall)
            noinstall=1
            ;;
        nompath)
            nompath=1
            ;;
        repo=*)
            repo="${x#repo=}"
            ;;
        rescue)
            rescue=1
            ;;
        resolution=*)
            resolution="${x#resolution=}"
            ;;
        serial|console=*)
            textinst=1
            ;;
        syslog=*)
            syslog="${x#syslog=}"
            ;;
        textinst)
            textinst=1
            ;;
        updates=*)
            updates="${x#updates=}"
            ;;
        usefbx)
            usefbx=1
            ;;
        vnc)
            vnc=1
            ;;
        vncconnect=*)
            vncconnect="${x#vncconnect=}"
            ;;
        vncpassword=*)
            vncpassword="${x#vncpassword=}"
            ;;
        xdriver=*)
            xdriver="${x#xdriver=}"
            ;;
        esac
done

# Check which rootfs to be installed
blist="/.target_build_list"
if [ -f "$blist" ]; then
    lines=`cat $blist | wc -l`
    if [ $lines -gt 1 ]; then
        echo ""
        echo "=============== Found the following products ==============="
        for lineno in `seq $lines`; do
            echo "  $lineno) `sed -n "${lineno}p" $blist | sed -e 's/^:://' -e 's/::/\t/g'`"
        done
        while true; do
            echo ""
            echo -n "Please enter your choice (0 to quit): "
            read choice
            right_choice=0
            if [ "$choice" = "0" ]; then
                exit 1
            fi
            for cnt in `seq $lines`; do
                if [ "$cnt" = "$choice" ]; then
                    right_choice=1
                    break
                fi
            done
            if [ $right_choice -eq 1 ]; then
                break
            else
                echo "Invalid choice: $choice, it should be one of: " `seq $lines`
            fi
        done
        prj_name="`sed -n "${choice}p" $blist | awk -F:: '{print $2}'`"
        entries=".buildstamp LiveOS Packages installer-config/ks.cfg"
        for f in $entries; do
            if [ -e /$f.$prj_name ]; then
                ln -sf `basename $f.$prj_name` /$f
            fi
        done
    fi
fi

case "$1" in
  start)
       # configure X, allowing user to override xdriver
       if [ -n "$xdriver" ]; then
           mkdir -p /etc/X11/xorg.conf.d/
           cat > /etc/X11/xorg.conf.d/00-xdriver.conf <<FOE
Section "Device"
        Identifier      "Videocard0"
        Driver  "$xdriver"
EndSection
FOE
       fi

       . /etc/profile
       username=root
       echo "Starting Anaconda"
       if [ -f /etc/X11/Xusername ]; then
           username=`cat /etc/X11/Xusername`
           # setting for rootless X
           chmod o+w /var/log
           chmod g+r /dev/tty[0-3]
           chmod o+rw /dev/input/*
           # hidraw device is probably needed
           if [ -e /dev/hidraw0 ]; then
               chmod o+rw /dev/hidraw*
           fi
       fi

       if [ -n "$textinst" ]; then
           anaconda_opts="$anaconda_opts --text"
	   # Quiet kernel logs, this can be undone in a kickstart file
	   echo 1 > /proc/sys/kernel/printk
       fi

       if [ -n "$vncpassword" ]; then
           echo "$vncpassword" > /tmp/vncpassword.dat
       fi

       for OPTIONS in vnc headless usefbx mpath nompath rescue cmdline; do
           if [ -n "${!OPTIONS}" ]; then
               anaconda_opts="$anaconda_opts --$OPTIONS"
           fi
       done

       for OPTIONS in resolution vncconnect xdriver syslog loglevel lang kbdtype keymap repo; do
           if [ -n "${!OPTIONS}" ]; then
               anaconda_opts="$anaconda_opts --$OPTIONS=${!OPTIONS}"
           fi
       done

       KICKSTART_FILE="/installer-config/ks.cfg"

       if [ -n "$ks" ]; then
           anaconda_opts="$anaconda_opts --kickstart=$ks"
       elif [ -e $KICKSTART_FILE ]; then
           anaconda_opts="$anaconda_opts --kickstart=/installer-config/ks.cfg"
       fi

       ROOT_IMAGE="/LiveOS/rootfs.img"
       ROOT_IMAGE_DEV="/dev/loop3"
       if [ -e $ROOT_IMAGE ]; then
           ROOT_IMAGE="`realpath $ROOT_IMAGE`"
           losetup -a | grep -q $ROOT_IMAGE
           if [ $? -eq 0 ]; then
               echo "Skipping mounting $ROOT_IMAGE since it is already setup."
           else
               losetup -r $ROOT_IMAGE_DEV $ROOT_IMAGE
               [ $? -eq 0 ] || exit 1
           fi
           anaconda_opts="$anaconda_opts --liveinst --method=livecd:$ROOT_IMAGE_DEV"
       elif [ -n "$liveinst" ]; then
               echo "ERROR: no $ROOT_IMAGE" >&2
               exit 1
       fi

       BOOTIF=`cat /proc/cmdline |xargs -n1 echo |grep BOOTIF=`
       BOOTIF=${BOOTIF#BOOTIF=01-}
       BOOTIF=${BOOTIF//-/:}
       FOUND_IFACE=0
       ignore_addr=""

       # Create Fedora-style network configuration files needed by anaconda
       NETDIR=/etc/sysconfig/network-scripts
       mkdir -p $NETDIR
       for i in `ls /sys/class/net`
       do
           touch $NETDIR/ifcfg-$i
           if [ "$bootifonly" != 1 -o "$BOOTIF" = "" -o ! -f /sys/class/net/$i/address ] ; then
               continue
           fi
           hwaddr=`cat /sys/class/net/$i/address`
           if [ "$hwaddr" != "$BOOTIF" ] ; then
               ignore_addr="mac:$hwaddr;$ignore_addr"
           else
               FOUND_IFACE=1
           fi
       done
       if [ $FOUND_IFACE = 1 -a "$ignore_addr" != "" ] ; then
           echo "" >> /etc/NetworkManager/NetworkManager.conf
           echo "[keyfile]" >> /etc/NetworkManager/NetworkManager.conf
           echo unmanaged-devices="${ignore_addr%;}" >> /etc/NetworkManager/NetworkManager.conf
       fi

       PRODUCT_IMG_FILE="/run/initramfs/live/images/product.img"
       PRODUCT_DISK="/tmp/product-disk"
       PRODUCT_DIR="/tmp/product"

       UPDATES_IMG_FILE="/run/initramfs/live/images/updates.img"
       UPDATES_DISK="/tmp/update-disk"
       UPDATES_DIR="/tmp/updates"

       if [ -e "$PRODUCT_IMG_FILE" ]; then
           mkdir $PRODUCT_DIR
           if [ ! -z "$(file $PRODUCT_IMG_FILE | grep 'gzip compressed data')" ]; then
               ( cd $PRODUCT_DIR ; gzip -dc $PRODUCT_IMG_FILE | cpio -id )
           else
               mkdir $PRODUCT_DISK
               mount -t auto $PRODUCT_IMG_FILE $PRODUCT_DISK
               cp -Rt $PRODUCT_DIR $PRODUCT_DISK/*
               umount $PRODUCT_DISK
               rmdir $PRODUCT_DISK
           fi
       fi

       if [ -e "$UPDATES_IMG_FILE" ]; then
           mkdir $UPDATES_DIR
           if [ ! -z "$(file $UPDATES_IMG_FILE | grep 'gzip compressed data')" ]; then
               ( cd $UPDATES_DIR ; gzip -dc $UPDATES_IMG_FILE | cpio -id )
           else
               mkdir $UPDATES_DISK
               mount -t auto $UPDATES_IMG_FILE $UPDATES_DISK
               cp -Rt $UPDATES_DIR $UPDATES_DISK/*
               umount $UPDATES_DISK
               rmdir $UPDATES_DISK
           fi
       fi

       # Set up the updates, if provided.
       if [ ! -z "$updates" ]; then
           if [ -e $UPDATES_IMG_FILE -o -e $UPDATES_DIR ]; then
               echo "The option updates= was provided, but an updates image already exists.  Please remove $UPDATES_IMG_FILE and $UPDATES_DIR and try again."
               exit 1
           fi

           # Add a barrier to ensure that networking is up before running curl
           #nm-online -q --timeout=30
           #
           #if [ $? -eq 0 ]; then
           #    curl --retry 3 --retry-max-time 30 -o /tmp/updates.img $updates
           #else
           #    echo "anaconda-init: Could not detect if NetworkManager was online."
           #    exit 1
           #fi

           mkdir $UPDATES_DIR
           # We officially support two updates.img formats:  a filesystem image, and
           # a compressed cpio blob.
           if [ ! -e /tmp/updates.img ]; then
               echo "The option updates= was provided, but an updates image could not be retrieved. Please verify the path and try again."
               exit 1
           elif [ ! -z "$(file /tmp/updates.img | grep 'gzip compressed data')" ]; then
               ( cd $UPDATES_DIR ; gzip -dc /tmp/updates.img | cpio -id )
           else
               mkdir $UPDATES_DISK
               mount -t auto /tmp/updates.img $UPDATES_DISK
               cp -Rt $UPDATES_DIR $UPDATES_DISK/*
               umount $UPDATES_DISK
               rmdir $UPDATES_DISK
           fi

           export PYTHONPATH=/tmp/updates:$PYTHONPATH
           export LD_LIBRARY_PATH=/tmp/updates:$LD_LIBRARY_PATH
           export PATH=/tmp/updates:$PATH
       fi

       # Add a barrier here to ensure that networking is up before running Anaconda
       #nm-online -q --timeout=30
       #if [ $? -eq 2 ]; then
       #    echo "anaconda-init: Could not detect if NetworkManager was online."
       #    exit 1
       #fi

       # Using su rather than sudo as latest 1.8.1 cause failure [YOCTO #1211]
       if [ -n "$noinstall" ]; then
           echo "Bypassing installer..."
       else
           su -l -c "$EXTRA_ENVS /usr/sbin/anaconda $anaconda_opts 2>&1" $username
           if [ "$stoponfail" != 1 ] ; then
               echo "Rebooting system..."
               /sbin/reboot -f
           fi
       fi

       if [ "$stoponfail" = 1 ] ; then
           killall Xorg
           stty sane
           echo ""
           echo "Starting FAIL shell"
           export HOME="/root"
           /bin/sh
       fi
  ;;

  stop)
        echo "Stopping Anaconda"
        killall anaconda
        killall Xorg
        killall Xvnc
  ;;

  restart)
        $0 stop
        sleep 1
        $0 start
  ;;

  *)
        echo "usage: $0 { start | stop | restart }"
  ;;
esac

exit 0

